//
//  RecruitDiliverymanViewController.m
//  Hui
//
//  Created by HawkingWang on 16/10/31.
//  Copyright © 2016年 Hui. All rights reserved.
//

#import "RecruitDiliverymanViewController.h"
#import "WebViewController.h"//网页Controller
#import "PublishPaymentView.h"//支付View

@interface RecruitDiliverymanViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate, UIScrollViewDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
/**配送员姓名*/
@property (weak, nonatomic) IBOutlet UITextField *deliveryManName;
/**选择性别*/
@property (weak, nonatomic) IBOutlet UIImageView *maleImage;
@property (weak, nonatomic) IBOutlet UIImageView *femaleImage;
/**配送员联系方式*/
@property (weak, nonatomic) IBOutlet UITextField *phone;
/**配送员真实姓名*/
@property (weak, nonatomic) IBOutlet UITextField *name;
/**配送员身份证号*/
@property (weak, nonatomic) IBOutlet UITextField *identityNumber;
/**上传身份证照片*/
//@property (weak, nonatomic) IBOutlet UIButton *uploadFront;
@property (weak, nonatomic) IBOutlet UIImageView *uploadFont;
@property (weak, nonatomic) IBOutlet UILabel *frontLabel;
//@property (weak, nonatomic) IBOutlet UIButton *uploadBack;
@property (weak, nonatomic) IBOutlet UIImageView *uploadBack;
@property (weak, nonatomic) IBOutlet UILabel *backLabel;
//@property (weak, nonatomic) IBOutlet UIButton *uploadHandHold;
@property (weak, nonatomic) IBOutlet UIImageView *uploadHandHold;
@property (weak, nonatomic) IBOutlet UILabel *HandHoldLabel;
@property (weak, nonatomic) IBOutlet UIImageView *payMarginImage;

@end

@implementation RecruitDiliverymanViewController
{
    NSString *_sex;
    NSString *_pay;
    NSMutableArray *_uploadImageArr;
    
    NSInteger _uploadNum;
    PublishPaymentView *_payView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;
    
    
    _scrollView.showsHorizontalScrollIndicator = NO;
    _sex = @"0";
    _pay = @"1";
    _uploadImageArr = [NSMutableArray arrayWithArray:@[@"0", @"0", @"0"]];
    
    
}

#pragma mark === 选择性别 ===
- (IBAction)chooseMale:(id)sender {
    [self resign];
    _sex = @"0";
    _maleImage.image = [UIImage imageNamed:@"right-touch"];
    _femaleImage.image = [UIImage imageNamed:@"right"];
}
- (IBAction)chooseFemale:(id)sender {
    [self resign];
    _sex = @"1";
    _maleImage.image = [UIImage imageNamed:@"right"];
    _femaleImage.image = [UIImage imageNamed:@"right-touch"];
}
#pragma mark === 上传照片 ===
- (IBAction)uploadFront:(id)sender {
    [self resign];
    [_uploadImageArr replaceObjectAtIndex:0 withObject:@"1"];
    _uploadNum = 0;
    [self uploadPic];
}
- (IBAction)uploadBack:(id)sender {
    [self resign];
    [_uploadImageArr replaceObjectAtIndex:1 withObject:@"1"];
    _uploadNum = 1;
    [self uploadPic];
}
- (IBAction)uploadHandHold:(id)sender {
    [self resign];
    [_uploadImageArr replaceObjectAtIndex:2 withObject:@"2"];
    _uploadNum = 2;
    [self uploadPic];
}

- (void)uploadPic{
    UIAlertController *alter = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    //选择、更改头像
    UIAlertAction *defaultAction1 = [UIAlertAction actionWithTitle:@"图库" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        // 显示照片选择控制器
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
        
        [imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
        // 2) 是否允许编辑
        [imagePicker setAllowsEditing:YES];
        
        // 3) 设置代理
        imagePicker.delegate = self;
        
        imagePicker.navigationBar.translucent = NO;
        imagePicker.navigationBar.tintColor = APPBLACK;
        imagePicker.navigationBar.barTintColor = [UIColor whiteColor];
        
        NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
        attrs[NSForegroundColorAttributeName] = APPBLACK;
        [[UINavigationBar appearance] setTitleTextAttributes:attrs];
        // 4) 显示照片选择控制器，显示modal窗口
        [self presentViewController:imagePicker animated:YES completion:nil];
        
    }];
    UIAlertAction *defaultAction2 = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 显示照片选择控制器
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
        [imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
        [imagePicker setAllowsEditing:YES];
        imagePicker.delegate = self;
        imagePicker.navigationBar.tintColor = [UIColor blackColor];
        [self presentViewController:imagePicker animated:NO completion:nil];
    }];
    [alter addAction:cancelAction];
    [alter addAction:defaultAction1];
    [alter addAction:defaultAction2];
    [self presentViewController:alter animated:NO completion:nil];
}




#pragma mark === 保障金 ===
/**保障金勾选*/
- (IBAction)payTheMargin:(id)sender {
    if ([_pay isEqualToString:@"1"]) {
        _pay = @"0";
        _payMarginImage.image = [UIImage imageNamed:@"right"];
    }else{
        _pay = @"1";
        _payMarginImage.image = [UIImage imageNamed:@"right-touch"];
    }
}
/**保障金说明*/
- (IBAction)marginIntroduction:(id)sender {
    WebViewController *web = [[WebViewController alloc] init];
    web.titleStr = @"保障金说明";
    [self presentViewController:web animated:YES completion:nil];
}

/**配送说明*/
- (IBAction)deliveryIntroduction:(id)sender {
    WebViewController *web = [[WebViewController alloc] init];
    web.titleStr = @"配送说明";
    [self presentViewController:web animated:YES completion:nil];
}

#pragma mark === 提交 ===
- (IBAction)commit:(id)sender {
    if ([_deliveryManName.text isEqualToString:@""]) {
        [EBUtility prompt:@"请输入配送员姓名" with:self];
    }else if ([_phone.text isEqualToString:@""]){
        [EBUtility prompt:@"请输入配送员电话" with:self];
    }else if (![EBUtility isMobileNumber:_phone.text]){
        [EBUtility prompt:@"请输入正确的联系方式" with:self];
    }else if ([_name.text isEqualToString:@""]){
        [EBUtility prompt:@"请输入真实姓名" with:self];
    }else if ([_identityNumber.text isEqualToString:@""]){
        [EBUtility prompt:@"请输入身份证号" with:self];
    }else if (![EBUtility validateIdentityCard:_identityNumber.text]){
        [EBUtility prompt:@"请输入正确的身份证号" with:self];
    }else if ([_uploadImageArr[0] isEqualToString:@"0"]){
        [EBUtility prompt:@"请上传身份证正面照" with:self];
    }else if ([_uploadImageArr[1] isEqualToString:@"0"]){
        [EBUtility prompt:@"请上传身份证反面照" with:self];
    }else if ([_uploadImageArr[2] isEqualToString:@"0"]){
        [EBUtility prompt:@"请上传手持身份证照" with:self];
    }else if ([_pay isEqualToString:@"0"]){
        [self applySucceed];
    }else{
        [self pay];
    }
}
- (void)applySucceed{
    __weak __typeof__ (self) weakSelf = self;
    [SVProgressHUD show];
    [SVProgressHUD showSuccessWithStatus:@"申请成功,等待审核"];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [SVProgressHUD dismiss];
        [weakSelf.navigationController popViewControllerAnimated:YES];
    });
}

- (void)pay{
    _payView = [[[NSBundle mainBundle] loadNibNamed:@"PublishPaymentView" owner:nil options:nil] lastObject];
    _payView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    _payView.backgroundColor = RGBACOLOR(0, 0, 0, 0.5);
    _payView.heightConstraint.constant = 113.5 * SCREEN_HEIGHT / 667;
    _payView.money.text = @"¥200.00";
    [[UIApplication sharedApplication].keyWindow addSubview:_payView];
    
    __weak __typeof__ (PublishPaymentView *)weakView = _payView;
    __weak __typeof__ (self) weakSelf = self;
    _payView.paymentViewClick = ^(int num){
        switch (num) {
            case 0:
                [weakView removeFromSuperview];
                break;
            case 1:
                DLog(@"充值成功");
            {
                [SVProgressHUD showSuccessWithStatus:@"支付成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakView removeFromSuperview];
                    [SVProgressHUD dismiss];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [weakView removeFromSuperview];
                        [SVProgressHUD dismiss];
                        [weakSelf applySucceed];
                    });
                });
            }
                break;
            default:
                break;
        }
    };
}

#pragma mark ===UIImagePicker代理方法 ===
//照片选择完成的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    // 获取编辑后的照片
    UIImage *image = [info[@"UIImagePickerControllerEditedImage"] fixOrientation];
    
    [picker dismissViewControllerAnimated:YES completion:^{
        switch (_uploadNum) {
            case 0:
                _frontLabel.hidden = YES;
                _uploadFont.image = image;
                break;
            case 1:
                _backLabel.hidden = YES;
                _uploadBack.image = image;
                break;
            case 2:
                _HandHoldLabel.hidden = YES;
                _uploadHandHold.image = image;
                break;
            default:
                break;
        }
    }];
}
//压缩图片
- (UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth
{
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = (targetWidth / width) * height;
    UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
    [sourceImage drawInRect:CGRectMake(0,0,targetWidth,  targetHeight)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}



#pragma mark === UITextFeildDelegate ===
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self resign];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self resign];
}
- (void)resign{
    [_name resignFirstResponder];
    [_phone resignFirstResponder];
    [_deliveryManName resignFirstResponder];
    [_identityNumber resignFirstResponder];
}

- (IBAction)back:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
